<template>
  <div class="dialog-form">
    <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="roleKey">
            <template #label>
              <span>
                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                权限字符
              </span>
            </template>
            <el-input v-model="form.roleKey" placeholder="请输入权限字符" :disabled="form.roleId ? true : false" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item label="显示顺序" prop="roleSort">
            <el-input-number v-model="form.roleSort" controls-position="right" :min="0" :step="1" :precision="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :value="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="菜单权限">
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
        <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          ref="menuRef"
          node-key="id"
          :check-strictly="!form.menuCheckStrictly"
          empty-text="加载中，请稍候"
          :props="{ label: 'label', children: 'children' }"
        ></el-tree>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { roleMenuTreeselect, treeselect as menuTreeselect } from "@/api/system/menu";
import { addRole, getRole, updateRole, deptTreeSelect } from "@/api/system/role";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const emits = defineEmits(['cancel', 'confirm'])
const menuRef = ref()
const roleRef = ref()

const form = ref({
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 0,
  status: "0",
  menuIds: [],
  deptIds: [],
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: undefined
})
const menuOptions = ref([])
const menuExpand = ref(false)
const menuNodeAll = ref(false)

const rules = {
  roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
  roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
  roleSort: [{ required: true, message: "显示顺序不能为空", trigger: "blur" }]
}

const pageInit = (roleId) => {
  if (roleId) {
    const roleMenu = getRoleMenuTreeselect(roleId)
    getRole(roleId).then(response => {
      form.value = response.data
      form.value.roleSort = Number(form.value.roleSort)
      nextTick(() => {
        roleMenu.then((res) => {
          let checkedKeys = res.checkedKeys
          checkedKeys.forEach((v) => {
            nextTick(() => {
              menuRef.value.setChecked(v, true, false);
            });
          });
        });
      })
    })
  } else {
    /** 查询菜单树结构 */
    menuTreeselect().then(response => {
      menuOptions.value = response.data
    })
  }
}

/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) {
  return roleMenuTreeselect(roleId).then(response => {
    menuOptions.value = response.menus;
    return response;
  });
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value) {
  let treeList = menuOptions.value;
  for (let i = 0; i < treeList.length; i++) {
    menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value) {
  menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value) {
  form.value.menuCheckStrictly = value ? true : false;
}

const onCancel = () => {
  emits('cancel')
}

const onConfirm = () => {
  roleRef.value.validate(valid => {
    if (valid) {
      if (form.value.roleId != undefined) {
        form.value.menuIds = getMenuAllCheckedKeys();
        updateRole(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          roleRef.value.resetFields()
          emits('confirm')
        });
      } else {
        form.value.menuIds = getMenuAllCheckedKeys();
        addRole(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          roleRef.value.resetFields()
          emits('confirm')
        });
      }
    }
  })
}

defineExpose({
  pageInit
})

</script>

<style lang="scss" scoped>

</style>